package com.zmn.mcc.admin.controller.permit.role;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.request.RequestUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.business.interfaces.role.RolePermitBService;
import com.zmn.mcc.model.entity.role.McRolePermit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author heguanghua
 * @since 2020/04/24 12:09
 */
@Controller
@RequestMapping("/permit/role/modify/")
public class PermitRoleModifyController extends PermitRoleBaseController {

    @Resource
    private RolePermitBService rolePermitBService;

    /**
     * 移除权限角色
     */
    @RequestMapping("cancel")
    @ResponseBody
    public ResponseDTO cancel(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "ids", defaultValue = "") String ids) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("未指定要取消对此权限已分配的角色");
        }

        List<String> groups = StringUtil.split(ids, GlobalConsts.SPLITER_DEFAULT, String.class);
        for (String group : groups) {
            List<Integer> idid = StringUtil.split(group, GlobalConsts.SPLITER_UNDERLINE, Integer.class);
            McRolePermit rolePermit = new McRolePermit();
            rolePermitService.deleteByKey(idid.get(1), idid.get(0));
        }
        return ResponseDTO.success(null, "操作成功");
    }

    /**
     * 新增权限角色
     */
    @RequestMapping("add")
    @ResponseBody
    public ResponseDTO add(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "keyId", defaultValue = "0") Integer permitId,
                           @RequestParam(value = "roleIds", defaultValue = "0") String roleIds) {

        String ip = RequestUtil.getRequestIp(request);
        if (NumberUtil.isNullOrZero(permitId)) {
            return ResponseDTO.fail("没有找到权限");
        }
        if (StringUtil.isBlank(roleIds)) {
            return ResponseDTO.fail("未指定授权角色");
        }
        rolePermitBService.addRolePermit(permitId, StringUtil.split(roleIds, Integer.class), getLoginStaff(), ip);
        return ResponseDTO.success(null, "操作成功");
    }
}
